import { Select } from "antd"
import React, { useEffect, useState } from "react"

const SelectAll = (props) => {
  const {
    defaultValue,
    onChange,
    withValueProps,
    selectRest,
    restProps,
    allowClear,
    mode,
    optionTemplate,
    dealOptions=[],

  } = props

  const getNewOptions = (disabled=false) => {
    return dealOptions.map(item => {
      item.ifDisabled = disabled
      item.children = item.label
      return item
    })
  }

  const allItem = {value: 'all',label: '全选'}
  const [allOptions, setAllOptions] = useState([])

  useEffect(() => {
    if (!dealOptions.length) return

    setAllOptions([allItem, ...getNewOptions()])

  }, [dealOptions])

  const handleSelectAllChange = (value=[], options) => {

    let newValue = [...value]
    let newOption = [...options]
    const index = value.indexOf('all')
    
    if (index === 0 && newValue.length >  1) {
      // console.log('找到到了all，在第一位，且选择了其他项')
      newValue.shift()
      newOption.shift()
      onChange(newValue, newOption)
      return
    }
    if (index !== -1) {
      // console.log('找到到了all')
      // console.log('getNewOptions()==>', getNewOptions())
      // console.log('');
      onChange(['all'], getNewOptions())
      return
    }
    // console.log('没有找到all')
    onChange(value, options)

  }

  return (
    <Select
      defaultValue={defaultValue}
      onChange={handleSelectAllChange}
      {...withValueProps}
      {...selectRest}
      {...restProps}
      allowClear={allowClear}
      mode={mode}
      // onFocus={() => console.log(dealOptions)}
    >
      {allOptions.map((option, index) => (
        <Select.Option key={index} value={option.value} disabled={option.ifDisabled}>
          {optionTemplate(option) || option.value + '-' + option.label}
        </Select.Option>
      ))}
    </Select>
  )
}

// export default SelectAll
export default React.memo( SelectAll )